import useUserStore from '@/store/modules/user.ts'
import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter'
import axios, { type AxiosRequestConfig } from 'axios'

interface RequestConfig extends Omit<AxiosRequestConfig, 'url' | 'method'> {}

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
  responseType: 'json',
  adapter: createUniAppAxiosAdapter(),
})

const HttpErrorMap = {
  401: '暂无权限，请先登录',
  403: '禁止访问',
  404: '资源不存在',
  500: '服务器错误',
  502: '网关错误',
  503: '服务不可用',
  504: '网关超时',
}

service.interceptors.request.use((config) => {
  const token = getToken()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

service.interceptors.response.use(
  (response) => {
    // 处理二进制响应（如文件下载）
    if (response.config.responseType === 'blob') {
      return response.data
    }

    const { code, data, message } = response.data
    const userStore = useUserStore()
    if (response?.data?.paySign) {
      return response.data
    }
    if (code === 401) {
      userStore.logout()
      // uni.showToast({
      //   title: '登录失效，请重新登录',
      //   icon: 'none',
      // })
      // uni.reLaunch({
      //   url: '/pages/home/index',
      // })
      return Promise.reject(new Error('登录失效，请重新登录'))
    }
    // 处理业务层错误
    if (code !== 200) {
      const errorMessage = message || '未知业务错误'
      console.error(errorMessage)
      return Promise.reject(response.data)
    }
    return response.data
  },
  (error) => {
    // 处理取消请求的特殊情况
    if (axios.isCancel(error)) {
      return Promise.reject(new Error('请求已取消'))
    }

    // 处理 HTTP 错误
    const status = error.response?.status as keyof typeof HttpErrorMap
    let errorMessage = error.message

    if (status) {
      errorMessage = HttpErrorMap[status] || `HTTP 错误: ${status}`

      if (status === 401) {
        // removeToken()
      }
    }

    return Promise.reject(new Error(errorMessage))
  },
)

const request = {
  get<T = any>(url: string, params?: any, config?: RequestConfig): Promise<T> {
    return service({ ...config, method: 'GET', url, params })
  },
  post<T = any>(url: string, data?: any, config?: RequestConfig): Promise<T> {
    return service({ ...config, method: 'POST', url, data })
  },
  put<T = any>(url: string, data?: any, config?: RequestConfig): Promise<T> {
    return service({ ...config, method: 'PUT', url, data })
  },
  patch<T = any>(url: string, data?: any, config?: RequestConfig): Promise<T> {
    return service({ ...config, method: 'PATCH', url, data })
  },
  delete<T = any>(url: string, params?: any, config?: RequestConfig): Promise<T> {
    return service({ ...config, method: 'DELETE', url, params })
  },
  request(method: string, url: string, data: any) {
    return new Promise((resolve, reject) => {
      service({ method, url, ...data })
        .then((res) => {
          resolve(res)
        })
        .catch((e) => {
          reject(e)
        })
    })
  },
}

export default request
